from typing import Dict, Any, Optional, List
from .payment_base import BasePaymentService, PaymentProvider, PaymentMethod
from .wechat_pay_service import WeChatPayService
from .alipay_service import AlipayService

class PaymentServiceFactory:
    """支付服务工厂"""
    
    _service_classes = {
        PaymentProvider.WECHAT_PAY: WeChatPayService,
        PaymentProvider.ALIPAY: AlipayService,
        # 可以添加其他支付服务商
        # PaymentProvider.STRIPE: StripeService,
    }
    
    @classmethod
    def create_service(cls, provider: PaymentProvider, config: Dict[str, Any]) -> BasePaymentService:
        """创建支付服务实例"""
        service_class = cls._service_classes.get(provider)
        if not service_class:
            raise ValueError(f"不支持的支付服务提供商: {provider}")
        
        return service_class(config)
    
    @classmethod
    def get_available_providers(cls) -> List[PaymentProvider]:
        """获取所有可用的支付服务提供商"""
        return list(cls._service_classes.keys())

class PaymentManager:
    """支付服务管理器"""
    
    def __init__(self):
        self.services: Dict[PaymentProvider, BasePaymentService] = {}
        self.default_provider: Optional[PaymentProvider] = None
    
    def register_service(self, provider: PaymentProvider, config: Dict[str, Any], is_default: bool = False):
        """注册支付服务"""
        service = PaymentServiceFactory.create_service(provider, config)
        self.services[provider] = service
        
        if is_default or not self.default_provider:
            self.default_provider = provider
    
    def get_service(self, provider: Optional[PaymentProvider] = None) -> Optional[BasePaymentService]:
        """获取支付服务"""
        if provider and provider in self.services:
            return self.services[provider]
        
        if self.default_provider:
            return self.services.get(self.default_provider)
        
        return None
    
    def get_services_for_method(self, payment_method: PaymentMethod) -> List[BasePaymentService]:
        """获取支持指定支付方式的所有服务"""
        services = []
        for service in self.services.values():
            if payment_method in service.get_supported_methods():
                services.append(service)
        return services
    
    def get_all_services(self) -> Dict[PaymentProvider, BasePaymentService]:
        """获取所有支付服务"""
        return self.services.copy()
    
    def get_supported_methods(self) -> Dict[PaymentProvider, List[PaymentMethod]]:
        """获取各服务商支持的支付方式"""
        supported_methods = {}
        for provider, service in self.services.items():
            supported_methods[provider] = service.get_supported_methods()
        return supported_methods

# 全局支付管理器实例
payment_manager = PaymentManager()